/*
 * SpawnedProcess.h
 *
 *  Created on:  Jun 6, 2009
 *      Author:  Zach Riggle A37627537
 *      Project: CSE410 Project 1
 */

#ifndef SPAWNEDPROCESS_H_
#define SPAWNEDPROCESS_H_

#include "ChildProcess.h"

/**
 * Spawned Process class.  Performs the actual 'work' for each command
 * that is entered by the user.
 *
 * Example:
 *   echo 123 | grep 1 | uniq
 * Would cause 3 SpawnedProcess objects to be instantiated.
 *
 */
class SpawnedProcess: protected ChildProcess {
public:
    SpawnedProcess();
    virtual ~SpawnedProcess();

    /**
     * Sets the four pipes that need to be closed before exiting.
     *
     * @param old
     * 		Pipe file descriptors from the LAST process.  These have not been
     * closed by the calling process, because they may be needed for IO piping.
     * @param new
     * 		Pipe file descriptors for THIS process.  These have not been closed
     * yet because they may be used to pipe IO to the next process.
     */
    void setPipesToClose(int old[2], int new_[2]);

    /**
     * Sets the file descriptors for IO redirection.
     *
     * @param fd
     * 		Array of integers, holding the file descriptors to be used.  Will
     * only check the first two values, and will redirect stdin and stdout
     * to those file descriptors.  The actual redirection does not take place
     * until execute() is called.
     */
    void redirect(int *fd);

    /**
     * Runs a command.
     *
     * @param args
     * 		Null-terminated list of null-terminated strings that comprise the
     * command and its arguments.  Similar to the second argument of execvp.
     * Note that 'custom' commands, e.g. 'hist','curr', etc. are also handled
     * here.
     */
    void execute(char **args);

private:
    int oldPipes[2];
    int newPipes[2];
};

#endif /* SPAWNEDPROCESS_H_ */
